// serverMiddleware.js

const lifecycle = process.env.npm_lifecycle_script || "";
const variable = (lifecycle.match(/NODE_ENV=(\w+)/) || [])[1]; // development|production|testing;
const isProduct = variable == "production";
const isTesting = variable == "testing";

export default (req, res, next) => {
    const host = req.headers.host;
    const path = req.url || "";

    if (isTesting) {
        // 禁止百度收录
        const agent = req.headers["user-agent"];
        const reg =
            /qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Feedfetcher-Google|Yahoo! Slurp|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot|ia_archiver|Tomato Bot/;

        if (path == "/robots.txt") {
            // robots
            res.writeHead(200, { "Content-Type": "text/plain" });
            res.write("User-agent: * \nDisallow: /");
            res.end();
        } else if (reg.test(agent)) {
            // 禁用爬虫
            res.writeHead(404);
            res.end();
        } else {
            next();
        }
    } else if (isProduct && /^podpartner\.com$/.test(host)) {
        res.writeHead(301, { Location: "https://www.podpartner.com" + path });
        res.end();
    } else {
        next();
    }
};
